package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> uploadImage(MultipartFile pic) throws IOException {
        if(ObjectUtils.isEmpty(pic)||pic.isEmpty()){
            throw new CustomException("文件不允许是空");
        }
        String contentType = pic.getContentType();
        if (!imageProperties.getTypeList().contains(contentType)) {
            imageProperties.getTypeList().stream()
                    .map(x->x.split("/")[1])
                    .collect(Collectors.joining(","));
            throw new CustomException("文件不允许是空");
        }

        String location = imageProperties.getLocation();
        File parent = new File(location);
        if(!parent.exists()){
            parent.mkdirs();
        }
        String originalFilename = pic.getOriginalFilename();
        String suffix = FileNameUtil.getSuffix(originalFilename);
        String filename= IdUtil.simpleUUID() + StrUtil.DOT + suffix;

        File destFile = new File(parent, filename);
        pic.transferTo(destFile);

        String path = imageProperties.getPrefix().endsWith(StrUtil.SLASH) ?
                imageProperties.getPrefix() + filename :
                imageProperties.getPrefix() + StrUtil.SLASH + filename;
        return ResultVO.success(path);
    }
}
